<template>
  <div>
    <!-- -----------------------------------------------------基本信息-------------------------------------------------------------- -->
    <el-divider>基本信息</el-divider>
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" inline class="rule-form">

      <div class="dialog_left">
        <el-form-item label="申请类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择采购类型" @change="handleOptions" style="width:100%">
            <el-option v-for="(item, i) in ['维修', '保养', '其他']" :key="i" :label="item" :value="i"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="ruleForm.type == 0" label="维修单" prop="orderId">
          <el-select v-model="ruleForm.orderId" filterable placeholder="请选择维修单" style="width:100%"
            @change="handleSelect">
            <el-option v-for="item in maintainArray" :key="item.repairId" :label="item.repairNum"
              :value="item.repairId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="ruleForm.type == 1" label="保养单" prop="orderId">
          <el-select v-model="ruleForm.orderId" filterable placeholder="请选择保养单" style="width:100%"
            @change="handleSelect">
            <el-option v-for="item in upkeepArray" :key="item.upkeepTaskId" :label="item.upkeepTaskNum"
              :value="item.upkeepTaskId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="申请仓库" prop="storehouseId">
          <el-cascader v-model="ruleForm.storehouseId" :options="storageOptionsList" @change="handleSelect"
            :props="{ expandTrigger: 'hover', label: 'storehouseName', value: 'storehouseId' }">
          </el-cascader>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="ruleForm.remark" placeholder="请输入备注信息" />
        </el-form-item>

      </div>
      <!-- -----------------------------------------------------添加采购品【按钮】及弹框-------------------------------------------------------------- -->
      <div class="dialog_btn">
        <el-button type="primary" icon="el-icon-circle-plus-outline" @click="handleAddPurchase">添加物料</el-button>
      </div>
      <Purchase ref="purchase_form" @click_create_submit="handleSlectList" />
      <!-- ---------------------------------------------------物料采购表格----------------------------------------------------------- -->
      <div class="dialog_table">
        <el-table :data="ruleForm.SubmitSelectList" style="width: 100%" max-height="450">
          <el-table-column label="序号" width="100">
            <template slot-scope="scope">
              <div> {{ scope.$index + 1 }} </div>
            </template>
          </el-table-column>
          <el-table-column prop="materialNum" label="物料编号" />
          <el-table-column prop="materialName" label="物料名称" />
          <el-table-column prop="typeName" label="类别" />
          <el-table-column prop="model" label="规格型号">
            <template slot-scope="{row}">
              <div> {{ row.model || '-' }} </div>
            </template>
          </el-table-column>
          <el-table-column prop="unitName" label="单位" />
          <el-table-column label="领料数量">
            <template slot-scope="scope">
              <el-form-item class="table_form_input" :prop="'SubmitSelectList.' + scope.$index + '.overplusAmount'"
                :rules="rules.fileNum">
                <el-input-number style="width:100%;margin-top: 20px;" :min="1" :max="scope.row.amount" :controls="false"
                  v-model="scope.row.overplusAmount" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="库存数量" />
          <el-table-column prop="remark" label="操作">
            <template slot-scope="scope">
              <el-button icon="el-icon-delete" type="danger" size="small" @click="handledelete(scope.$index)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-divider>附件信息</el-divider>
      <FileUpload v-model="ruleForm.file" :limit="1" :fileSize="50" style="width:385px"
        :fileType="['xls', 'xlsx', 'doc', 'docx', 'pdf', 'jpg', 'png']">
      </FileUpload>
      <!-- ---------------------------------------------------审核信息----------------------------------------------------------- -->
      <el-divider>审核信息</el-divider>
      <div class="rule_form_audit">
        <el-form-item label="审核人" prop="auditVosUser">
          <el-select v-model="ruleForm.auditVosUser" collapse-tags multiple placeholder="请选择审核人" style="width:100%">
            <el-option v-for="dict in allUserData" :key="dict.index" :label="dict.userName" :value="dict.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="" style="margin-left:110px">
          <span v-for="(tag, index) in tagUserList" :key="index">
            <el-tag closable disable-transitions @close="tagChange(tag, index)">
              <span>{{ tag.name }}</span>
            </el-tag>
            <span style="font-size:28px;position: relative;top: 5px;">
              <template v-if="index !== tagUserList.length - 1">
                <i class="el-icon-caret-right"></i>
              </template>
            </span>
          </span>

        </el-form-item>
        <el-form-item label="抄送人">
          <el-select v-model="ruleForm.auditVosType" multiple placeholder="请选择抄送人" style="width:100%">
            <el-option v-for="dict in allUserData" :key="dict.index" :label="dict.userName" :value="dict.userId">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
    </el-form>
    <!-- ---------------------------------------------------提交及取消【按钮】----------------------------------------------------------- -->
    <div class="form_btn">
      <el-button type="primary" @click="handleSubmitForm">提交</el-button>
      <el-button @click="handleCloseForm">取消</el-button>
    </div>
  </div>
</template>

<script>
import { add, replacementList, maintainList, upkeepList, getuserlist, listDetail, RegionalList } from '@/api/deviceConsumable/acquisitionapplication'
import Purchase from './purchase.vue'
/** 表单参数 ------------------------------------------------------------------------------------------------------------------------ */
const ruleForm = {
  type: 2, //采购类型（0维修 1保养 2其他）
  orderId: null,//维修和保养 id
  storehouseId: [],//仓库id集合
  remark: "", //备注
  file: '',//附件
  SubmitSelectList: [],// 列表提交总数据展示
  auditVosUser: [],// 审核人
  auditVosType: []// 抄送人
}
/** ---------------------------------------------------------------------------------------------------------------------------------- */

export default {
  name: 'detailedform',
  components: {
    Purchase
  },
  data () {
    return {
      ruleForm: Object.assign({}, ruleForm),
      allUserData: [],//用户信息列表
      storageOptionsList: [],//申请仓库数组
      maintainArray: [],//维修单数组
      upkeepArray: [],//保养单数组
      formFLag: false,
      /** 表单规则 --------------------------------------------------------------------------------------------------------------------- */
      rules: {
        type: [
          { required: true, message: '请选择采购类型', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        orderId: [
          { required: true, message: '请选择工单号', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        storehouseId: [
          { required: true, message: '请选择申请仓库', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入备注', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        fileNum: [
          { required: true, message: '请输入领料数量', trigger: 'blur' }
        ],
        auditVosUser: { required: true, message: '请选择审核人', trigger: 'change' },
        auditVosType: { required: true, message: '请选择抄送人', trigger: 'change' },
      }
    }
  },
  computed: {
    // 审核人数据转换--------------------------
    tagUserList () {
      let Arr = []
      this.ruleForm.auditVosUser.map(item => {
        this.allUserData.map(value => {
          if (item === value.userId) {
            Arr.push({
              userId: value.userId,
              name: value.userName
            })
          }
        })
      })
      return Arr
    },
  },
  created () {
    this.getlist()
  },
  methods: {
    // 重新申请的回显事件--------------
    handlegetFormlist (id) {
      if (id) {
        this.formFLag = true
        listDetail(id).then(({ data: res }) => {
          console.log(res);
          // 申请类型及维修单和保养单数据回显--------------
          this.ruleForm.type = res.type * 1;
          this.handleOptions(res.type);
          this.ruleForm.orderId = res.orderId;
          // 申请仓库数据回显--------------
          RegionalList({ level: 2 }).then(({ data }) => {
            const rule = this.getParentIdList(data, res.storehouseId)
            this.ruleForm.storehouseId = rule
          })
          // 备注数据回显-----------------
          this.ruleForm.remark = res.remark || '';

          this.ruleForm.SubmitSelectList = res.pickConsumableVos.map(item => {
            return {
              ...item.consPriceAndAmountVo,
              amount: item.amount,
              overplusAmount: item.overplusAmount
            }
          })
        })
      } else {
        this.formFLag = false
      }
    },
    // ----------添加物料【按钮】 ------------------
    handleAddPurchase () {
      if (this.ruleForm.type == 0 || this.ruleForm.type == 1) {
        if (this.ruleForm.orderId && this.ruleForm.storehouseId.length) {
          let equipmentid
          if (this.ruleForm.type == 1) {
            // 保养单
            const rule = this.upkeepArray.filter((item) => this.ruleForm.orderId == item.upkeepTaskId)
            equipmentid = rule[0].equipmentAccountId
          }
          if (this.ruleForm.type == 0) {
            // 保养单
            const rule = this.maintainArray.filter((item) => this.ruleForm.orderId == item.repairId)
            equipmentid = rule[0].equipmentAccountId
          }
          let [arr] = [...this.ruleForm.storehouseId].reverse()
          const params = {
            storehouseId: arr,
            equipmentAccountId: equipmentid,
            status: '0'
          }
          // console.log(params);
          this.$refs['purchase_form'].openDialog(params)
        } else {
          this.$message({
            message: `请选择${['维修单', '保养单'][this.ruleForm.type]}工单号和申请仓库！`,
            type: 'warning'
          });
        }
      }
      if (this.ruleForm.type == 2) {
        if (this.ruleForm.storehouseId.length) {
          let [arr] = [...this.ruleForm.storehouseId].reverse()
          const params = {
            storehouseId: arr,
            status: '0'
          }
          console.log(params);
          this.$refs['purchase_form'].openDialog(params)
        } else {
          this.$message({
            message: `请选择申请仓库！`,
            type: 'warning'
          });
        }
      }
    },
    async getlist () {
      // 用户列表接口-------------------------
      const userdata = await getuserlist();
      this.allUserData = userdata.data
      // 获取仓库列表---------------------------
      const { data: storage } = await replacementList()
      // 入库仓库：三级树组重组数据
      const arborescenceList = this.handleTree(storage, "storehouseId");
      arborescenceList.forEach(item => {// 二级数组禁用。不可选
        if (item.children) {
          const arr = item.children.map(j => {
            if (j.children) {
              return Object.assign({}, j, { 'disabled': false })
            } else {
              return Object.assign({}, j, { 'disabled': true })
            }
          })
          item.children = arr
        }
      })
      let ancestors = arborescenceList.map(item => {// 一级数组禁用。不可选
        if (item.children) {
          return Object.assign({}, item, { 'disabled': false })
        } else {
          return Object.assign({}, item, { 'disabled': true })
        }
      })
      this.storageOptionsList = ancestors
    },
    // 申请类型选择事件-----------------------------
    handleOptions (i) {
      if (i == 0) {
        // 维修单列表---------------------------------------
        maintainList({ orderByColumn: 'repairId', isAsc: 'desc' }).then(({ data: res }) => {
          this.maintainArray = res
        })
      }
      if (i == 1) {
        // 保养单列表---------------------------------------
        upkeepList({ orderByColumn: 'upkeepTaskId', isAsc: 'desc' }).then(({ data: res }) => {
          this.upkeepArray = res
        })
      }
      this.ruleForm.orderId = null
      this.ruleForm.SubmitSelectList = []

    },
    // 表单采购类型选择器切换
    handleSelect () {
      this.ruleForm.SubmitSelectList = []
    },
    // 接收子组件勾选后的数据
    handleSlectList (val) {
      console.log(val);
      this.ruleForm.SubmitSelectList.push(...val)
      const arr = [...this.ruleForm.SubmitSelectList, ...val]
      const rule = this.removedup(arr, 'consumableBaseId')
      this.ruleForm.SubmitSelectList = rule.map(item => {
        return {
          ...item,
          overplusAmount: null
        }
      })
    },
    //列表的删除事件
    handledelete (index) {
      this.ruleForm.SubmitSelectList.splice(index, 1)
    },
    // 审核人删除事件
    tagChange (val, index) {
      this.ruleForm.auditVosUser.splice(index, 1)
    },
    // 表单总提交事件
    handleSubmitForm () {
      // console.log('Form总提交数据',this.ruleForm);
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // -------------------------------------------------------重组表格列表提交数据--------------------------------------------

          // -------------------------------------------------审核人和抄送人数据重组------------------------------------------
          const examine = this.ruleForm.auditVosUser.map(item => {
            return {
              userId: item,
              userType: 0
            }
          })//审核人
          const copy = this.ruleForm.auditVosType.map(item => {
            return {
              userId: item,
              userType: 1
            }
          })// 抄送人
          // console.log('审核人',examine);
          // console.log('抄送人',copy);
          // ----------------------------------------------------总数据拼接----------------------------------------------------
          let [arr] = [...this.ruleForm.storehouseId].reverse()
          let data = {
            type: this.ruleForm.type,
            storehouseId: arr,
            file: this.ruleForm.file,
            remark: this.ruleForm.remark,
            pickConsumableVos: this.ruleForm.SubmitSelectList.map(item => {
              return {
                consumableBaseId: item.consumableBaseId,
                amount: item.overplusAmount
              }
            }),
            auditVos: examine.concat(copy)
          }
          if (this.ruleForm.type != 2) {
            data.orderId = this.ruleForm.orderId
          }
          add(data).then(() => {
            this.$emit('form_submit_click')
            this.$message.success('申请领料成功！');
          })
        } else {
          this.$message.error('提交表单验证信息不通过，请重新输入');
        }
      })


    },
    // 表单取消事件
    handleCloseForm () {
      this.$emit('form_submit_click')
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog_table {
  margin-top: 20px;
}


/* el-descriptions-item 文字居中 */
::v-deep .el-descriptions__body .el-descriptions__table .el-descriptions-item__cell {
  text-align: center;
}

.rule_form_audit {
  width: 24%;
  margin: auto;
}

.dialog_btn {
  margin: 10px 45px;
}

.form_btn {
  width: 42%;
  display: flex;
  justify-content: center;
  margin: 50px auto 20px auto;
}
</style>